<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择预约状态" clearable>
          <el-option
            v-for="dict in appointment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:patientsAppointment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:patientsAppointment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:patientsAppointment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:patientsAppointment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="patientsAppointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预约记录ID" align="center" prop="id" />
      <el-table-column label="就诊人ID" align="center" prop="patientsId" />
      <el-table-column label="预约日期" align="center" prop="appointmentDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointmentDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="appointmentTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.appointmentTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="医生姓名" align="center" prop="doctorName">
        <template #default="scope">
          <span>{{ scope.row.doctorName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="appointment_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            v-if="scope.row.status === 1"
            link
            type="primary"
            icon="Check"
            @click="completeAppointment(scope.row)"
          >完成就诊
          </el-button>
          <!-- 取消预约按钮 -->
          <el-button
          v-if="scope.row.status === 0 || scope.row.status === 1"
            link
            type="primary"
            icon="Close"
            @click="cancelAppointment(scope.row)"
          >取消预约
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:patientsAppointment:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:patientsAppointment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改就诊人预约挂号对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
    <el-form ref="patientsAppointmentRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="就诊人" prop="patientsId">
        <el-input v-model="form.patientsName" placeholder="请选择就诊人" style="width: 70%;" readonly />
        <el-button type="primary" @click="openPatientSelectDialog" slot="append" style="width: 30;">选择就诊人</el-button>
        <!-- 新增一个隐藏的输入框用于存储就诊人 ID -->
        <el-input v-model="form.patientsId" type="hidden" />
      </el-form-item>
      <el-form-item label="预约日期" prop="appointmentDate">
        <el-date-picker clearable
          v-model="form.appointmentDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约日期"
          @change="handleAppointmentDateChange">
        </el-date-picker>
      </el-form-item>
      <!-- 只有在选择了预约日期后才显示预约时间下拉框 -->
      <el-form-item label="预约时间" prop="appointmentTime" v-if="form.appointmentDate">
        <el-select v-model="form.appointmentTime" placeholder="请选择预约时间">
          <el-option
            v-for="option in appointmentTimeOptions"
            :key="option"
            :label="option"
            :value="option">
          </el-option>
        </el-select>
        <!-- 当没有可用排班信息时显示提示 -->
        <span v-if="appointmentTimeOptions.length === 0 && form.appointmentDate">当前日期无可用挂号</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
    <!-- 选择就诊人对话框 -->
    <el-dialog :title="选择就诊人" v-model="patientSelectDialogVisible" width="500px" append-to-body>
      <el-table :data="patientsList" @row-click="selectPatient" style="width: 100%;" stripe>
        <!-- <el-table-column prop="id" label="就诊人 ID"></el-table-column> -->
        <el-table-column prop="name" label="就诊人姓名" align="center"></el-table-column>
        <el-table-column prop="idNumber" label="身份证号" align="center"></el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="patientSelectDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PatientsAppointment">
import { listPatientsAppointment, getPatientsAppointment, delPatientsAppointment, addPatientsAppointment, updatePatientsAppointment } from "@/api/manage/patientsAppointment";
import { listPatients } from "@/api/manage/patients";
import { getInfo } from "@/api/login";
import { listSchedule } from "@/api/manage/schedule"; // 引入 listSchedule 函数
import { getDoctor } from "@/api/manage/doctor";
import { ElMessageBox } from 'element-plus';


const { proxy } = getCurrentInstance();
const { appointment_status } = proxy.useDict('appointment_status');

const patientsAppointmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const currentUserId = ref(null); // 用于存储当前登录用户的 ID
const patientsList = ref([]);
const patientSelectDialogVisible = ref(false);
const appointmentTimeOptions = ref([]); // 存储预约时间下拉框选项
const isAdmin = ref(false); // 用于判断是否为管理员

const data = reactive({
  form: {
    patientsId: null,
    patientsName: null,
    appointmentDate: null,
    appointmentTime: null,
    status: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null,
    patientsId: null,
    userId: null,
    doctorId: null,
    appointmentDate: null,
    appointmentTime: null,
    status: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    patientsId: [
      { required: true, message: "就诊人ID不能为空", trigger: "blur" }
    ],
    appointmentDate: [
      { required: true, message: "预约日期不能为空", trigger: "blur" }
    ],
    appointmentTime: [
      { required: true, message: "预约时间不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询就诊人预约挂号列表 */
async function getList() {
    loading.value = true;
    try {
        const response = await listPatientsAppointment(queryParams.value);
        const appointments = response.rows;
        console.log(appointments);
        // 遍历每条预约记录，查询医生姓名
        for (const appointment of appointments) {
            const scheduleQuery = {
                date: appointment.appointmentDate
                // 这里不使用具体的开始和结束时间，因为值班时间可能覆盖多个预约
            };
            const scheduleResponse = await listSchedule(scheduleQuery);
            const schedules = scheduleResponse.rows;

            const appointmentStartTime = new Date(`2000-01-01 ${appointment.appointmentTime.split('-')[0]}`);
            const appointmentEndTime = new Date(`2000-01-01 ${appointment.appointmentTime.split('-')[1]}`);

            let matchedSchedule = null;
            for (const schedule of schedules) {
                const scheduleStartTime = new Date(`2000-01-01 ${schedule.startTime}`);
                const scheduleEndTime = new Date(`2000-01-01 ${schedule.endTime}`);
                // 检查预约时间是否在排班时间范围内
                if (appointmentStartTime >= scheduleStartTime && appointmentEndTime <= scheduleEndTime) {
                    matchedSchedule = schedule;
                    break;
                }
            }

            if (matchedSchedule) {
                const doctorId = matchedSchedule.doctorId;
                const doctorResponse = await getDoctor(doctorId);
                appointment.doctorName = doctorResponse.data.name; 
            } else {
                appointment.doctorName = '未查询到医生信息';
            }
        }

        patientsAppointmentList.value = appointments;
        total.value = response.total;
        loading.value = false;
    } catch (error) {
        console.error('查询就诊人预约挂号列表失败:', error);
        loading.value = false;
    }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    patientsId: null,
    userId: null,
    doctorId: null,
    appointmentDate: null,
    appointmentTime: null,
    status: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("patientsAppointmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加就诊人预约挂号";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  try {
    const response = await getPatientsAppointment(_id);
    form.value = response.data;
    // 根据 patientsId 查询就诊人姓名
    if (form.value.patientsId) {
      const query = {
        pageNum: 1,
        pageSize: 1,
        id: form.value.patientsId
      };
      
      const patientResponse = await listPatients(query);
      console.log('就诊人列表:', patientResponse);
      if (patientResponse.rows.length > 0) {
        form.value.patientsName = patientResponse.rows[0].name; // 假设就诊人姓名的字段名为 name
      }
    }

    open.value = true;
    title.value = "修改在线问诊";
  } catch (error) {
    console.error('获取问诊信息失败:', error);
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["patientsAppointmentRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePatientsAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPatientsAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除就诊人预约挂号编号为"' + _ids + '"的数据项？').then(function() {
    return delPatientsAppointment(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/patientsAppointment/export', {
    ...queryParams.value
  }, `patientsAppointment_${new Date().getTime()}.xlsx`)
}

// 打开就诊人选择对话框
async function openPatientSelectDialog() {
  if (!currentUserId.value) {
    console.error('未获取到当前登录用户的 ID');
    return;
  }
  try {
    const query = {
      pageNum: 1,
      pageSize: 100, // 假设查询足够多的就诊人，可根据实际情况调整
      userId: currentUserId.value
    };
    const response = await listPatients(query);
    console.log('就诊人列表:', response);
    patientsList.value = response.rows; 
    patientSelectDialogVisible.value = true;
  } catch (error) {
    console.error('查询就诊人列表失败:', error);
  }
}

// 选择就诊人
function selectPatient(row) {
  // 记录就诊人 ID
  form.value.patientsId = row.id; 
  // 记录就诊人姓名
  form.value.patientsName = row.name; 
  patientSelectDialogVisible.value = false;
}

// 处理预约日期选择变化
async function handleAppointmentDateChange(date) {
  if (date) {
    try {
      const scheduleQuery = {
        date: date
        // 可以根据需要添加其他查询参数
      };
      const scheduleResponse = await listSchedule(scheduleQuery);
      const schedules = scheduleResponse.rows;
      console.log('医生排班数据:', schedules);

      const reservedQuery = {
        appointmentDate: date
      };
      const reservedResponse = await listPatientsAppointment(reservedQuery);
      const reservedAppointments = reservedResponse.rows;
      console.log('已预约数据:', reservedAppointments);

      appointmentTimeOptions.value = [];

      if (schedules.length === 0) {
        // 当没有排班信息时，不生成时间选项
        console.log('当前日期无可用挂号数量');
      } else {
        schedules.forEach(schedule => {
          const startTime = new Date(`2000-01-01 ${schedule.startTime}`);
          const endTime = new Date(`2000-01-01 ${schedule.endTime}`);
          const numSlots = schedule.availableSlots;

          // 计算每个挂号的时间间隔（毫秒）
          const slotDuration = (endTime - startTime) / numSlots;
          console.log('时间间隔:', startTime, endTime, numSlots, slotDuration);

          for (let i = 0; i < numSlots; i++) {
            const slotStartTime = new Date(startTime.getTime() + i * slotDuration);
            const slotEndTime = new Date(slotStartTime.getTime() + slotDuration);
            const option = `${formatTime(slotStartTime)}-${formatTime(slotEndTime)}`;

            // 检查该时间段是否已被预约
            const isReserved = reservedAppointments.some(appointment => {
              const appointmentStartTime = new Date(`2000-01-01 ${appointment.appointmentTime.split('-')[0]}`);
              const appointmentEndTime = new Date(`2000-01-01 ${appointment.appointmentTime.split('-')[1]}`);
              return slotStartTime >= appointmentStartTime && slotEndTime <= appointmentEndTime;
            });

            if (!isReserved) {
              appointmentTimeOptions.value.push(option);
            }
          }
        });
      }
      console.log('预约时间选项:', appointmentTimeOptions.value);
    } catch (error) {
      console.error('查询医生排班数据或已预约数据失败:', error);
    }
  } else {
    appointmentTimeOptions.value = [];
  }
}

// 格式化时间函数
function formatTime(date) {
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${hours}:${minutes}`;
}

// 获取当前登录用户信息并判断是否为管理员
const checkAdminRole = async () => {
  try {
    const response = await getInfo();
    const roles = response.roles || [];
    // 假设管理员角色编码为 'admin'，根据实际情况修改
    isAdmin.value = roles.some(role => role === 'admin'); 
    console.log('是否为管理员:', isAdmin.value);
  } catch (error) {
    console.error('获取登录用户信息失败:', error);
  }
};

// 完成就诊的方法
const completeAppointment = async (row) => {
  try {
    await ElMessageBox.confirm('是否确定完成就诊？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const updatedData = {
      ...row,
      status: 2 // 将状态设置为 2
    };

    await updatePatientsAppointment(updatedData);

    const index = patientsAppointmentList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      patientsAppointmentList.value[index] = updatedData;
    }

    ElMessageBox.alert('完成就诊成功', '提示', { type: 'success' });
  } catch (error) {
    if (error.name === 'CancelError') {
      console.log('用户取消了完成就诊操作');
    } else {
      console.error('完成就诊失败:', error);
      ElMessageBox.alert('完成就诊失败，请稍后重试', '提示', { type: 'error' });
    }
  }
};

// 取消预约的方法
const cancelAppointment = async (row) => {
  try {
    await ElMessageBox.confirm('是否确定取消预约？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const updatedData = {
      ...row,
      status: 3 // 将状态设置为 3
    };

    await updatePatientsAppointment(updatedData);

    const index = patientsAppointmentList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      patientsAppointmentList.value[index] = updatedData;
    }

    ElMessageBox.alert('取消预约成功', '提示', { type: 'success' });
  } catch (error) {
    if (error.name === 'CancelError') {
      console.log('用户取消了取消预约操作');
    } else {
      console.error('取消预约失败:', error);
      ElMessageBox.alert('取消预约失败，请稍后重试', '提示', { type: 'error' });
    }
  }
};

// 在组件挂载时获取当前登录用户的 ID 并根据角色设置查询参数
onMounted(async () => {
  await checkAdminRole();
  try {
    const response = await getInfo();
    console.log('当前登录用户的 ID:', response);
    if (response.code === 200) {
      currentUserId.value = response.user.userId;
      if (isAdmin.value) {
        // 如果是管理员，不设置 userId 参数，查询全部用户记录
        queryParams.value.userId = null;
      } else {
        // 如果不是管理员，设置 userId 参数，查询自己的记录
        queryParams.value.userId = currentUserId.value;
      }
      getList(); // 调用 getList 方法获取记录
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
});

// getList();
</script>
